/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.ar.hibernate.scanning;

import static net.paoding.rose.RoseConstants.DOMAIN_DIRECTORY_NAME;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.paoding.rose.impl.scanning.AbstractScanner;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileType;

/**
 * 
 * @author zhiliang.wang [qieqie.wang@paoding.net]
 * 
 */
public class DomainScannerImpl extends AbstractScanner implements DomainScanner {

	private List<Class<?>> domainClasses = new ArrayList<Class<?>>();

	// --------------------------------------------------------------------

	@Override
	public List<Class<?>> getDomainClasses() {
		return Collections.unmodifiableList(domainClasses);
	}

	// --------------------------------------------------------------------

	@Override
	protected void clear() {
		domainClasses.clear();
	}

	@Override
	protected boolean isFolderMatched(FileObject folderObject) {
		return DOMAIN_DIRECTORY_NAME.equals(folderObject.getName()
				.getBaseName());
	}

	@Override
	protected void handleWithFolder(FileObject rootObject,
			FileObject matchedRootFolder, FileObject thisFolder)
			throws IOException {
		logger.info("found domain folder in " + thisFolder);
		FileObject[] children = thisFolder.getChildren();

		// 分两个循环，先处理类文件，再处理子目录，使日志更清晰
		for (FileObject child : children) {
			if (!child.getType().equals(FileType.FOLDER)) {
				FileObject resource = child;
				handleDomainResource(rootObject, resource);
			}
		}
		for (FileObject child : children) {
			if (child.getType().equals(FileType.FOLDER)) {
				handleWithFolder(rootObject, matchedRootFolder, child);
			}
		}
	}

	protected void handleDomainResource(FileObject rootObject,
			FileObject resource) throws FileSystemException {
		FileName fileName = resource.getName();
		String bn = fileName.getBaseName();
		if (bn.endsWith(".class") && bn.indexOf('$') == -1) {
			addDomainClass(rootObject, resource);
		}
	}

	private void addDomainClass(FileObject rootObject, FileObject resource)
			throws FileSystemException {
		String className = rootObject.getName().getRelativeName(
				resource.getName());
		className = StringUtils.removeEnd(className, ".class");
		className = className.replace('/', '.');
		for (int i = domainClasses.size() - 1; i >= 0; i--) {
			Class<?> clazz = domainClasses.get(i);
			if (clazz.getName().equals(className)) {
				logger.info("domain: skip replicated class " + className
						+ " in " + resource.getName());
				return;
			}
		}
		try {
			domainClasses.add(Class.forName(className));
			logger.info("domain: found class, name=" + className);
		} catch (ClassNotFoundException e) {
			logger.error("", e);
		}
	}

	@Override
	protected String getDefaultJarName() {
		return super.getDefaultJarName() + ", *-domain.jar";
	}

}
